package com.paw.hand.gateway.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author lvzihai
 * @date 2021/6/16
 * @date 2021/6/16
 **/
@Slf4j
@Component
public class RouteInterceptor implements HandlerInterceptor {

  @Autowired
  private RestTemplate restTemplate;
  @Autowired
  private DiscoveryClient discoveryClient;

  @Override
  public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HttpHeaders httpHeaders = new HttpHeaders();
    String requestUrl = request.getRequestURI();
    if(StrUtil.isNotEmpty(request.getQueryString())){
      String query = URLDecoder.decode(request.getQueryString(),"UTF-8");
      requestUrl =requestUrl+"?"+query;
    }
    log.info("requestUrl {}",requestUrl);
    // 注册中心获取注册的服务
//    List<ServiceInstance> instances = discoveryClient.getInstances("paw-dogs-sky-service");
//    String ipAddr = instances.get(0).getUri().toString();
    // 加载路由映射 如配置文件、配置中心、redis、数据库
    Map<String,String> routerMap = new HashMap<>(16);
    routerMap.put("/sky-api","paw-dogs-sky-service");
    String routerKey = requestUrl;
    if(requestUrl.indexOf("/",1)>0){
      routerKey = requestUrl.substring(0,requestUrl.indexOf("/",1));
    }
    if(routerMap.containsKey(routerKey)){
      String serverName = routerMap.get(routerKey);
      // 做地址映射
      String targetUrl  = "http://"+requestUrl.replaceFirst(routerKey,serverName);

      log.info("requestUrl {} ==> targetUrl {}",requestUrl, targetUrl);

      ResponseEntity<String> responseEntity;
      if("POST".equalsIgnoreCase(request.getMethod())){
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        Map<String, String[]> paramMap = request.getParameterMap();
        for (String paramName: paramMap.keySet()) {
          params.addAll(paramName, Arrays.asList(paramMap.get(paramName)));
        }
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Object> requestEntity = new HttpEntity<>(params, httpHeaders);
        responseEntity = restTemplate.postForEntity(targetUrl, requestEntity, String.class);
      }else{
        responseEntity = restTemplate.getForEntity(targetUrl, String.class);
      }

      try {
        response.setStatus(responseEntity.getStatusCodeValue());
        String responseBody = responseEntity.getBody();
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(responseBody);
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return false;
    }
    return true;
  }

  @Override
  public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
  }

  @Override
  public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
  }
}
